import axios from 'axios'
import { ElMessage } from 'element-plus'

// Create axios instance for API requests
const service = axios.create({
  baseURL: 'http://localhost:5003', // 修复API的base_url，移除重复的/api前缀
  timeout: 15000, // 请求超时时间
  withCredentials: true // 允许携带cookie
})

// Request interceptor
service.interceptors.request.use(
  config => {
    // Add any request headers if needed
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    console.error('Response error:', error)
    if (error.response) {
      ElMessage({
        message: `请求失败: ${error.response.status} - ${error.response.statusText}`,
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.request) {
      ElMessage({
        message: '无法连接到服务器，请检查网络连接',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      ElMessage({
        message: error.message || '请求发生错误',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service 